<?php

/**
 * Well Framework
 * 
 * Contains Front Controller pattern class
 * 
 * @package     Well
 *
 * @author Valerii Lazarevych <valeriy.fremar@gmail.com>
 */

/**
 * Request class
 * 
 * Modeling request data entity
 */
class Request
{
    /**
     * $_REQUEST
     * 
     * @access private
     * @var type array
     */
    private $properties;
    
    /**
     * Contains all feedback message from controllers handling request
     *
     * @access private
     * @var type array
     */
    private $feedback   =   array();
    
    /**
     * Call $this->init()
     *      RequestRegistry::setRequest($this)
     */
    public function __construct()
    {
        $this->init();                
    }
    
    /**
     * Make initialize
     * 
     * @return
     */
    public function init() 
    {
        //get & save $_REQUEST
        if (isset($_SERVER['REQUEST_METHOD'])){
            
            $this->properties   =   $_REQUEST;
            
            $this->properties['reqScript'] = strstr( $_SERVER['REQUEST_URI'], '.php', true );
            
            return;
        }
        
        //get & save $_SERVER[argv]
        foreach( $_SERVER['argv'] as $arg){
            
            if ( strpos($arg, '=') ){
                
                list($key,$val) = explode('=', $arg);
                
                $this->setProperty($key, $val);
            }
         }
    }
    
    /**
     * Get element from this->properties[key]
     * 
     * @param string $key
     * @return mixed $_REQUEST || ARGS[$key]
     */
    public function getProperty($key = null)
    {
        if( $key === null ) {
            return $this->properties;    }
        
        return isset($this->properties[$key])  ? $this->properties[$key]  : null;
    }
    
    /**
     * Set val to this->properties[$key]
     * 
     * @param string $key
     * @param mixed $val 
     */
    public function setProperty( $key, $val )
    {
        $this->properties[$key] =  $val;
    }
    
    /**
     * Add response message to this->feedback
     * 
     * @param string $msg 
     */
    public function addFeedback( $msg )
    {
        array_push($this->feedback, $msg);
    }
    
    /**
     * Get all response messages to this request
     */
    public function getFeedback()
    {
        return $this->feedback;
    }
    
    /**
     * Transform array feedback to one string
     * 
     * @param string $separator 
     */
    public function getFeedbackString( $separator = '\n' )
    {
        return implode($separator, $this->feedback);
    }                    
}

